package network;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Observable;

public class Connexion extends Observable {
	String ip;
	int port;
	SocketAdmin socket;
	Protocol proto;
	boolean state;
	
	public Connexion(Protocol p){
		this.state = false;
		this.proto = p;
	}
	
	public boolean getState(){
		return this.state;
	}
	
	
	public void connect(String ip, int port){
		if(!state){
			this.ip = ip;
			this.port = port;
			
			try {
				socket = new SocketAdmin(this.ip,this.port,this.proto);
				this.state = true;
			} catch (UnknownHostException e) {
				System.err.println("[Admin][Connexion] Client introuvable");
			} catch (IOException e) {
				System.err.println("[Admin][Connexion] Creation de la socket impossible");
			}
			setChanged();
	        notifyObservers();
		}
	}
	
	public void disconnect(){
		if(state){
			try {
				socket.close();
			} catch (IOException e) {
				System.err.println("[Admin][Connexion] Fermeture de la socket impossible");
			}
			this.state = false;
			setChanged();
	        notifyObservers();
		}
	}

	/**
	 * Fonction envoi un objet au client
	 * 
	 * @param Object 
	 */
	
	public void send(Object o){
		if(state){
			try {
				socket.send(o);
			} catch (IOException e) {
				System.err.println("[Admin][Connexion] Erreur envoi, fermeture de la socket");
				//e.printStackTrace();
				disconnect();
			}
		}
	}
}
